<template>
  <el-container>
    <el-header>
      <div
        style="display: flex; justify-content: flex-start; align-items: center"
      >
        <!-- 表格与图表切换 -->
        <el-radio-group v-model="radio1" @change="changeDiffWayShowData">
          <el-radio label="图表" border>图表</el-radio>
          <el-radio label="数据" border>数据</el-radio>
        </el-radio-group>
        <!-- 字段组选择 -->
        <el-select
          v-model="cabinet.history"
          @change="changeFileds"
          style="margin-left: 5%"
        >
          <el-option
            v-for="item in cabinet.horizontalFields"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictLabel"
          />
        </el-select>
        <!-- 时间选择 -->
        <div style="width: 20%; margin-left: 5%">
          <el-date-picker
            class="datetime-picker"
            v-model="state.stateTime"
            :disabled-date="pickerOptions"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            @change="getValue"
          ></el-date-picker>
        </div>
      </div>
    </el-header>
    <el-main>
      <!-- 图表数据 -->
      <Echarts v-if="state.EchartsShow" ref="EchartsRef" />
      <!-- 表格数据 -->
      <History v-if="state.HistoryShow" ref="HistoryTableRef" />
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import {
  ref,
  provide,
  onMounted,
  reactive,
  onBeforeUnmount,
  inject,
} from "vue";
import { TimeOfPeriod, timeFormat, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useAssetSite } from "@/store/backend/Assets/site";
import { useConfig } from "@/store/config";
import { useElectricData } from "@/store/backend/DataM/RealTime";
import History from "./history.vue";
import Echarts from "./echarts.vue";

const cabinet = useAssetCabinet();
const dictionary = useDictionary();
const site = useAssetSite();
const config = useConfig();
const realTime = useElectricData();
const dictOperation = inject("dictOperation") as any;

const HistoryTableRef = ref();
const EchartsRef = ref();

const state: {
  defaultFileds: any[];
  HistoryShow: boolean;
  EchartsShow: boolean;
  comSearch: any;
  stateTime: any[];
} = reactive({
  defaultFileds: [],
  HistoryShow: false,
  EchartsShow: true,
  comSearch: { form: {} },
  stateTime: [],
});

// const value = ref("温度");
const radio1 = ref("图表");

//重写获取当月第一天的方法
class NewTimeOfPeriod extends TimeOfPeriod {
  getStart(): any {
    let date = new Date();
    date.setDate(1);
    // let startDay = date.toLocaleDateString().replace(/\//g, "-");
    let startDay =
      date.getFullYear() +
      "-" +
      JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
      "-" +
      JSON.stringify(date.getDate()).padStart(2, "0");
    startDay = startDay + " 00:00";
    console.log("重写获取当月第一天的方法", startDay);
    return startDay;
  }
}
const newTimeFunc = new NewTimeOfPeriod();

//重写字典处理
type dictObj = (arr: any[]) => anyObj;
class NewDictOperation extends DictOperation {
  getDictData: dictObj = (arr: any[]) => {
    let obj: any = {};
    for (let i = 0, len = arr.length; i < len; i++) {
      obj[arr[i].dictLabel] = arr[i].remark;
    }
    return obj;
  };
  //获取字典
  getDictionary = (
    specificClass: any, //pinia仓库类
    dictText: string, //字典名称
    filed: string, //仓库存储的经过处理后的字典对象
    dictStore: string //仓库存储的原始字典数组
  ) => {
    if (
      JSON.stringify(specificClass.tags) == "{}" ||
      !(filed == "" ? true : specificClass.tags[filed]) ||
      JSON.stringify(dictionary.moreTags[dictText]) == "{}"
    ) {
      dictionary.getDictInfo(dictText).then((res: any) => {
        let tempTags = dictOperation.getDictData(res);
        dictionary.moreTags[dictText] = tempTags;
        specificClass.$patch((state: any) => {
          if (filed != "") {
            state.tags[filed] = tempTags;
          }
          state.typeCategoryFormat = this.getDictData(res);
          state.horizontalFields = res;
          state[dictStore] = res;
          cabinet.history = res[0].dictLabel;
        });
      });
    } else {
      cabinet.history = cabinet.horizontalFields[0].dictLabel;
    }
  };
}
const newDictOperation = new NewDictOperation();
//限制用户只能选择到当天的日期
const pickerOptions = (time: Date) => {
  // return time.getTime() > Date.now() - 1 * 24 * 60 * 60 * 1000;
  return time.getTime() > Date.now();
};

//选择时间
const getValue = (value: any) => {
  console.log("选择时间", value);
  if (value) {
    //更新仓库存储时间
    cabinet.beginTime = state.stateTime[0] + ":00";
    cabinet.endTime = state.stateTime[1] + ":00";
  } else {
    //清空仓库存储时间
    cabinet.beginTime = "";
    cabinet.endTime = "";
  }
  if (radio1.value === "数据") {
    state.HistoryShow = false;
    state.EchartsShow = false;
    setTimeout(() => {
      state.HistoryShow = true;
    }, 500);
  } else {
    state.HistoryShow = false;
    state.EchartsShow = false;
    setTimeout(() => {
      state.EchartsShow = true;
    }, 500);
  }
};

//获取当前月的第一天与当前时间
const getTime = () => {
  state.stateTime[0] = newTimeFunc.getStart();
  state.stateTime[1] = timeFormat("", "yyyy-mm-dd hh:MM");
  //首次更新仓库存储时间
  cabinet.beginTime = state.stateTime[0] + ":00";
  cabinet.endTime = state.stateTime[1] + ":00";
};
getTime();

//选择不同字段组显示
const changeFileds = (value: any) => {
  console.log("选择不同字段组显示", value, typeof value);

  if (radio1.value === "数据") {
    state.HistoryShow = false;
    state.EchartsShow = false;
    setTimeout(() => {
      state.HistoryShow = true;
    }, 500);
  } else {
    state.HistoryShow = false;
    state.EchartsShow = false;
    setTimeout(() => {
      state.EchartsShow = true;
    }, 500);
  }
};

//选择不同方法展示数据
const changeDiffWayShowData = (value: any) => {
  console.log("选择不同方法展示数据", value);
  if (value === "图表") {
    state.EchartsShow = true;
    state.HistoryShow = false;
  } else {
    state.HistoryShow = true;
    state.EchartsShow = false;
  }
};

//获取字典
const getDictionary = () => {
  //获取机柜类型的字典
  dictOperation.getDictionary(
    cabinet,
    "sys_cabinet_type",
    "cabinetType",
    "type"
  );
  //获取卧式机柜字段组合（与告警类别统一）的字典
  newDictOperation.getDictionary(
    cabinet,
    "sys_warning_category",
    "categoryName",
    "cabinetFields"
  );
};
getDictionary();

onMounted(() => {});
onBeforeUnmount(() => {
  cabinet.history = "";
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("cabinet", cabinet);
provide("site", site);
provide("dictionary", dictionary);
provide("config", config);
provide("realTime", realTime);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
